package com.github.m6d21.sso.common.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import org.junit.Test;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2019/3/13 Wed 16:17:00
 * @since 1.0.0
 */
public class DigitalUtil {

//    private DigitalUtil(){}

    public BigDecimal integerToBigDecimal(Integer i) {
        BigDecimal bigDecimal = new BigDecimal(i);
        return bigDecimal;
    }

    @Test
    public void test1() {
        int d = 100;
        BigDecimal bigDecimal = new BigDecimal(d);
//        System.out.println(bigDecimal);
//        System.out.println(bigDecimal.movePointLeft(2));
//        System.out.println(new BigDecimal(100.01).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        System.out.println(new BigDecimal(100.051).setScale(1,RoundingMode.HALF_UP));
        System.out.println(new BigDecimal(100.03).setScale(1,RoundingMode.HALF_UP));
        System.out.println(removeTailZero(new BigDecimal(1000.005),2,RoundingMode.UP));
    }

    public BigDecimal removeTailZero(BigDecimal bigDecimal, int scale, RoundingMode mode) {
        if (bigDecimal == null) {
            throw new NullPointerException("BigDecimal不能为null");
        }

        if (scale < 0) {
            throw new IllegalArgumentException("scale不能小于0");
        }

        if(mode==null){
            mode =RoundingMode.UP;
        }

        String s = bigDecimal.setScale(scale, mode).toString();
        String str[] = s.split("\\.");
        int len = str.length;
        String decimalsPart = str[len - 1];

        int newScale = decimalsPart.length();

        String reverseDecimalsPart = new StringBuilder(decimalsPart).reverse().toString();
        for(Character c:reverseDecimalsPart.toCharArray()){
            if('0'==c){
                newScale--;
            }else {
                break;
            }
        }

        return bigDecimal.setScale(newScale, mode);
    }

    @Test
    public void test2() {
    }


}
